# @Author: dpf
# @Date  : 2024/12/04/15:54
from entity.BookModel import Book
from util import dbUtil


def add(book: Book):
    con = None
    try:
        con = dbUtil.getCon()
        cursor = con.cursor()
        cursor.execute(
            f"insert into book values (null,'{book.bookName}','{book.author}','{book.sex}','{book.price}','{book.bookTypeId}','{book.bookDesc}') ")
        return cursor.rowcount
    except Exception as e:
        print(e)
        con.rollback()
        return 0
    finally:
        dbUtil.closeCon(con)


def list(s_book: Book):
    con = None
    try:
        con = dbUtil.getCon()
        cursor = con.cursor()
        sql = " select b.id as id,bookName,author,bookTypeName,sex,price,bookDesc from book b left  join book_type bt on b.bookTypeId = bt.id where 1=1 "
        if s_book != None:
            if s_book.bookName.strip() != '':
                sql += " and b.bookName like '%" + s_book.bookName + "%'"
            if s_book.author.strip() != '':
                sql += " and b.author like '%" + s_book.author + "%'"
            if s_book.bookTypeId != 0:
                sql += " and b.bookTypeId = " + str(s_book.bookTypeId)
        print(sql)
        cursor.execute(sql)
        return cursor.fetchall()
    except Exception as e:
        print(e)
        con.rollback()
        return None
    finally:
        dbUtil.closeCon(con)


def update(book: Book):
    con = None
    try:
        con = dbUtil.getCon()
        cursor = con.cursor()
        print(
            f"update book set bookName='{book.bookName}',author='{book.author}',sex='{book.sex}',price={book.price},bookTypeId={book.bookTypeId},bookDesc='{book.bookDesc}' where id={book.id}")
        cursor.execute(
            f"update book set bookName='{book.bookName}',author='{book.author}',sex='{book.sex}',price={book.price},bookTypeId={book.bookTypeId},bookDesc='{book.bookDesc}' where id={book.id}")
        return cursor.rowcount
    except Exception as e:
        print(e)
        con.rollback()
        return 0
    finally:
        dbUtil.closeCon(con)


def delete(id):
    con = None
    try:
        con = dbUtil.getCon()
        cursor = con.cursor()
        cursor.execute(f" delete from  book  where id = {id} ")
        return cursor.rowcount
    except Exception as e:
        print(e)
        con.rollback()
        return 0
    finally:
        dbUtil.closeCon(con)
